package com.koron.dynamic.controller;

import com.koron.bean.app.AppBean;
import com.koron.bean.base.Response;
import com.koron.common.core.util.SpringContextUtil;
import com.koron.dynamic.dataSource.DynamicDataSource;
import com.koron.dynamic.dataSource.DynamicDataSourceContextHolder;
import com.koron.dynamic.service.AppDataSourceService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName ThreadLocalController
 * @description
 * @Author zhouj
 * @Date 2021/7/14 14:15
 */
@RestController
@RequestMapping("/dynamic")
public class ThreadLocalController {

    @Autowired
    AppDataSourceService appDataSourceService;

    @GetMapping("/setThreadLocal")
    public Response<String> setThreadLocal(String mark,String id){

        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtil.getBean("dynamicDataSource");

        AppBean appBean = appDataSourceService.findDataSourceByKey(mark);
        if (appBean == null) {
            //没找到不设置
        }else {

            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setJdbcUrl(appBean.getDbHost());
            dataSource.setUsername(appBean.getDbUser());
            dataSource.setPassword(appBean.getDbPassword());
            dataSource.setDriverClassName(appBean.getDbDriverClassName());
            dynamicDataSource.addDataSources(mark,dataSource);
            DynamicDataSourceContextHolder.setDataSourceKey(mark);
        }
        return Response.success(appDataSourceService.queryData(id));
    }

    @GetMapping("/queryData")
    public Response<String> queryData(String id){
        return Response.success(appDataSourceService.queryData(id));
    }

}
